package se.lth.eit.eit060.proj2.server;

import java.io.*;

import javax.net.ssl.*;
import javax.security.cert.X509Certificate;

import myRules.Control;

import se.lth.eit.eit060.proj2.initiation.Utility;

public class MyServer {

	private SSLContext ctx;

	public static void main(String[] e) {
		MyServer s = new MyServer();
	}

	public MyServer() {
		ctx = Utility.generate("server.jks", "password".toCharArray());
		while(true){
		listen();
		System.out.println("Server died, restarting.");
		}
	}

	public void listen() {
		Control p = new Control();
		Logger l = new Logger();
		SSLSocket ssl = null;
		SSLServerSocket sslsocket = null;
		BufferedReader in = null;
		SSLSession session = null;
		try {
			SSLServerSocketFactory factory = ctx.getServerSocketFactory();
			sslsocket = (SSLServerSocket) factory
					.createServerSocket(Utility.PORT);
			sslsocket.setNeedClientAuth(true);
			ssl = (SSLSocket) sslsocket.accept();

			PrintWriter out = new PrintWriter(ssl.getOutputStream(),
					true);
			in = new BufferedReader(new InputStreamReader(
					ssl.getInputStream()));
			String inputLine, outputLine;
			//Can be used for login.
			/*outputLine = "Contact";
			out.println(outputLine);*/
			session = ssl.getSession();
			X509Certificate crt = null;
			try {
				crt = (X509Certificate) session.getPeerCertificateChain()[0];
			} catch (SSLPeerUnverifiedException e1) {
				e1.printStackTrace();
			}
			String id = null;
			try{
				id = crt.getSubjectDN().getName().split("=")[1].split(",")[0];
			}catch(Exception e){
				System.out.println("Identification error.");
				return; //Should be break later.
			}
			while ((inputLine = in.readLine()) != null) {
				String[] text = inputLine.split(Utility.SPLIT);
				System.out.println("RECORD"+text[1]);
				if(text.length>1){
				outputLine = p.parse(text[0], id, text[1],inputLine.substring(text[0].length()+text[1].length()+Utility.SPLIT.length()*2) , sslsocket.getInetAddress().toString());//p.parse(id,inputLine,sslsocket.getInetAddress().toString());
				}else{
					l.log(id,"NO ACTION", "NA", sslsocket.getInetAddress().toString());
					outputLine = Utility.FULLWARNING;
				}
				System.out.println("SERVER:"+outputLine);
				out.println(outputLine);
			};
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ssl.close();
			sslsocket.close();
			in.close();
			session.invalidate();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
